<script setup lang="ts">
import type { Props } from './utils/types'

defineOptions({
    name: 'ItemVideo'
})

const $props = defineProps<Props>()

const isShowVideo = shallowRef<boolean>(false)

function onMouseover() {
    isShowVideo.value = true
}

function onMouseout() {
    isShowVideo.value = false
    if (!videoDom.value) return
}

watch(isShowVideo, (newValue) => {
    if (newValue) {
        nextTick(() => {
            if (!videoDom.value) return
            if (videoDom.value.paused) {
                videoDom.value.playbackRate = 2.0
                videoDom.value.play().catch(error => {
                    console.error('播放失败:', error);
                })
            }
        })
    } else {
        nextTick(() => {
            if (!videoDom.value) return
            if (!videoDom.value.paused) {
                videoDom.value.pause();
            }
        })
    }
})

const videoDom = shallowRef<HTMLAudioElement>()
</script>

<template>
    <div class="item-video" @mouseenter="onMouseover" @mouseleave="onMouseout">
        <div class="cover">
            <img v-if="image" :src="image" alt="image">
        </div>
        <Transition>
            <div class="video" v-show="isShowVideo">
                <video autoplay playsinline muted ref="videoDom" v-if="sample">
                    <source :src="sample" type="video/mp4" />
                </video>
            </div>
        </Transition>
    </div>
</template>

<style lang="scss" scoped>
.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}

.item-video {
    width: 100%;
    position: relative;
    cursor: pointer;

    .cover {
        width: 100%;
        height: 100%;
        background-color: #dadada;
        display: flex;
        justify-content: center;
        align-items: center;

        img {
            width: 100%;
            height: 100%;
            display: block;
            object-fit: cover;
        }
    }

    .video {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: black;

        video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

    }
}
</style>